<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Category_books extends MX_Controller
{

    private $module = 'category_books';
    private $table = 'category';

    function __construct()
    {
        parent::__construct();
        $this->load->model($this->module . '_model', 'model');
        $this->load->model('admincp_modules/admincp_modules_model');
        if ($this->uri->segment(1) == 'admincp') {
            if ($this->uri->segment(2) != 'login') {
                if (!$this->session->userdata('userInfo')) {
                    header('Location: ' . PATH_URL . 'admincp/login');
                    return false;
                }
                $get_module = $this->admincp_modules_model->check_modules($this->uri->segment(2));
                $this->session->set_userdata('ID_Module', $get_module[0]->id);
                $this->session->set_userdata('Name_Module', $get_module[0]->name);
            }
            $this->template->set_template('admin');
            $this->template->write('title', 'Admin Control Panel');
        }
    }

    /*------------------------------------ Admin Control Panel ------------------------------------*/
    public function admincp_index()
    {
        modules::run('admincp/chk_perm', $this->session->userdata('ID_Module'), 'r', 0);
        $default_func = 'order';
        $default_sort = 'ASC';
        $data = array(
            'module' => $this->module,
            'module_name' => $this->session->userdata('Name_Module'),
            'default_func' => $default_func,
            'default_sort' => $default_sort
        );
        $this->template->write_view('content', 'BACKEND/index', $data);
        $this->template->render();
    }


    public function admincp_update($id = 0)
    {
        if ($id == 0) {
            modules::run('admincp/chk_perm', $this->session->userdata('ID_Module'), 'w', 0);
        } else {
            modules::run('admincp/chk_perm', $this->session->userdata('ID_Module'), 'r', 0);
        }
        $result[0] = array();
        if ($id != 0) {
            $result = $this->model->getDetailManagement($id);
        }
        $data = array(
            'result' => $result[0],
            'module' => $this->module,
            'id' => $id,
            'category' => $this->getCategory($result[0]->parent_id)
        );
        $this->template->write_view('content', 'BACKEND/ajax_editContent', $data);
        $this->template->render();
    }

    public function admincp_save()
    {
        $perm = modules::run('admincp/chk_perm', $this->session->userdata('ID_Module'), 'w', 1);
        if ($perm == 'permission-denied') {
            print $perm;
            exit;
        }
        if ($_POST) {
            //Upload Image
            $fileName = '';
            if ($_FILES) {
                if (isset($_FILES['fileAdmincp']['error'])) {
                    $typeFileImage = strtolower(substr($_FILES['fileAdmincp']['type'], 0, 5));
                    if ($typeFileImage == 'image') {
                        $tmp_name = $_FILES['fileAdmincp']["tmp_name"];
                        $file_name = $_FILES['fileAdmincp']['name'];
                        $ext = strtolower(substr($file_name, -4, 4));
                        if ($ext == 'jpeg') {
                            $fileName = time() . '_' . md5(substr($file_name, 0, -5)) . '.jpg';
                        } else {
                            $fileName = time() . '_' . md5(substr($file_name, 0, -4)) . $ext;
                        }
                    } else {
                        print 'Only upload Image.';
                        exit;
                    }
                }
            }
            //End Upload Image

            $id = $this->model->saveManagement($fileName);
            if ($id) {
                // Update left menu for Category of news
//                $this->update_left_menu($id);

                $this->admincp_clean_cache();
                $result['message'] = 'success';
                $result['id'] = $id;
                echo json_encode($result);
                exit;
            }
        }
    }

    function admincp_viewchild()
    {
        if (!isset($_POST)) {
            show_404();
        }
        $perm = modules::run('admincp/chk_perm', $this->session->userdata('ID_Module'), 'd', 1);
        if ($perm == 'permission-denied') {
            print $perm;
            exit;
        }
        $html = '<tr class="sub-category"><td colspan="6" style=""><table style="background: #F3F3F3;border-width: 0 1px 1px 1px;border-style: solid;border-color: #dddddd" cellspacing="0" cellpadding="0" border="0" width="100%">';
        $html .= '<tr>
            <th class="th_no_cursor" width="40">No.</th>
            <th class="th_left th_no_cursor">Tên</th>
            <th width="100">Action</th>
            <th width="100"><div id="status" class="sort icon_no_sort">Trạng thái</div></th>
            <th class="th_last" width="150"><div id="created" class="sort icon_sort_asc">Ngày tạo</div></th>
            </tr>';
        $id = $this->input->post('id');
        if ($id) {
            $result = $this->model->getCategory($id);
            $i = 0;
            if ($result) {
                foreach ($result as $r1) {
                    if ($r1->status == 0) {
                        $check = 'uncheck_16x16.png';
                    } else {
                        $check = 'check_16x16.png';
                    }
                    $i++;
                    $html .= '<tr>';
                    $html .= '<td>' . $i . '</td>';
                    $html .= '<td class="th_left"><a href="' . PATH_URL . 'admincp/' . $this->module . '/update/' . $r1->id . '">' . $r1->name . '</a></td>';
                    $html .= '<td><a href="javascript:void(0)" onclick="deleteSub(' . $r1->id . ',this)"><i class="fa fa fa fa-eraser"></i></a></td>';
                    $html .= '<td><a href="javascript:void(0)" onclick="updateStatus(' . $r1->id . ',' . $r1->status . ',' . $this->module . ')">
                <img alt="Checked item" src="' . PATH_URL . 'assets/admin/images/icons/' . $check . '"/></a></td>';
                    $html .= '<td>' . date('d-m-Y H:i:s', strtotime($r1->created)) . '</td>';
                    $html .= '</tr>';
                }
            } else {
                $html .= '<tr><td colspan="5">No have submenu</td></tr>';
            }
        }
        $html .= '</table></td></tr>';
        echo($html);
    }

    public function admincp_delete()
    {
        $perm = modules::run('admincp/chk_perm', $this->session->userdata('ID_Module'), 'd', 1);
        if ($perm == 'permission-denied') {
            print $perm;
            exit;
        }
        if ($this->input->post('id')) {
            $id = (int)$this->input->post('id');
            modules::run('admincp/saveLog', $this->module, $id, 'Delete', 'Delete');
            $this->admincp_clean_cache();
        }
    }

    public function admincp_ajaxLoadContent()
    {
        $this->load->library('AdminPagination');
        $config['total_rows'] = $this->model->getTotalsearchContent();
        $config['per_page'] = $this->input->post('per_page');
        $config['num_links'] = 3;
        $config['func_ajax'] = 'searchContent';
        $config['start'] = $this->input->post('start');
        $this->adminpagination->initialize($config);

        $result = $this->model->getsearchContent($config['per_page'], $this->input->post('start'));
        $data = array(
            'result' => $result,
            'per_page' => $this->input->post('per_page'),
            'start' => $this->input->post('start'),
            'module' => $this->module
        );
        $this->session->set_userdata('start', $this->input->post('start'));
        $this->load->view('BACKEND/ajax_loadContent', $data);
    }

    public function admincp_ajaxUpdateStatus()
    {
        $perm = modules::run('admincp/chk_perm', $this->session->userdata('ID_Module'), 'w', 1);
        if ($perm == 'permission-denied') {
            print '<script type="text / javascript">show_perm_denied()</script>';
            $status = $this->input->post('status');
            $data = array(
                'status' => $status
            );
        } else {
            modules::run('menu_category/UpdateStatus', $this->input->post('id'), $this->input->post('status'));
            if ($this->input->post('status') == 0) {
                $status = 1;
            } else {
                $status = 0;
            }
            $data = array(
                'status' => $status
            );
            modules::run('admincp/saveLog', $this->module, $this->input->post('id'), 'status', 'update', $this->input->post('status'), $status);
            $this->db->where('id', $this->input->post('id'));
            $this->db->update(PREFIX . $this->table, $data);
            $this->db->where('category_id', $this->input->post('id'));
            $this->db->update(PREFIX . 'books', $data);
            $this->admincp_clean_cache();
        }

        $update = array(
            'status' => $status,
            'id' => $this->input->post('id'),
            'module' => $this->module
        );
        $this->load->view('BACKEND/ajax_updateStatus', $update);
    }

    function admincp_change_data()
    {
        if ($this->model->moveDatabase() == false) {
            echo "Đã tồn tại dữ liệu";
        }
    }

    function admincp_clean_cache()
    {
//delete_cache_path($this->config,'tin-tuc');
//delete_cache_path($this->config,'kinh-nghiem');
    }

    function getCategory($id_ = 0)
    {
        $html = '';
        $result = $this->model->getCategory();
        if ($result == false) {
            $html .= '<option value="0">Parent</option>';
        } else {
            $html .= '<option value="0">Parent</option>';
            foreach ($result as $r1) {
                if ($id_ == $r1->id) {
                    $select = 'selected';
                } else {
                    $select = '';
                }
                $html .= '<option value="' . $r1->id . '" ' . $select . '>' . $r1->name . '</option>';

                $result2 = $this->model->getCategory($r1->id);
                if ($result2 != false) {
                    foreach ($result2 as $r2) {
                        $html .= '<option value="' . $r2->id . '"> - ' . $r2->name . '</option>';
                    }
                }
            }
        }
        return $html;
    }

    /*------------------------------------ End Admin Control Panel --------------------------------*/

    /*------------------------------------ BEGIN Admin Control Panel --------------------------------*/
    public function index()
    {
        show_404();
    }

    function showCategory($option)
    {
        $html = '';
        $parent = $this->model->fetch('*', PREFIX . $this->table, "status = 1 AND parent_id = 0 AND term_id = 4", 'order', 'asc');
        if (!empty($parent)) {
            foreach ($parent as $p) {
                if ($option == 'li') {
                    $html .= '<li><a href="' . PATH_URL . $p->slug . '.html">' . $p->name . '</a>';
                } elseif ($option == 'option') {
                    $html .= '<option value="' . $p->id . '">' . $p->name . '</option>';
                }
                $children = $this->model->fetch('*', PREFIX . $this->table, "status = 1 AND parent_id = '" . $p->id . "' AND term_id = 4", 'order', 'asc');
                //  var_dump($children);
                $html .= '<ul>';
                if (!empty($children)) {
                    foreach ($children as $c) {
                        if ($option == 'li') {
                            $html .= '<li><a href="' . PATH_URL . $c->slug . '.html">' . $c->name . '</a></li>';
                        }elseif ($option == 'option') {
                            $html .= '<option value="' . $c->id . '">' .'- '. $c->name . '</option>';
                        }
                    }
                }
                $html .= '</li></ul>';
            }
        }
        return $html;
    }

    function blockCategory()
    {
        $value = array(
            'category' => $this->showCategory('li'),
        );
        $this->load->view('FRONTEND/blocks/list_category_block', $value);
    }
    function optionCategory(){
        $value = array(
            'category' => $this->showCategory('option'),
        );
        $this->load->view('FRONTEND/blocks/list_category_block', $value);
    }

    function category($slug)
    {
        $slug = mysql_real_escape_string($slug);
        if ($slug == 'ebooks' || $slug == 'luan-van' || $slug == 'bai-tap-lon') {
            $type = typeSlugBook($slug);
            $RESULT_LIST = $this->model->fetch('*', 'cli_books', "type = '{$type}' AND status = 1", 'created', 'desc', 0, 2);
            $view_page = 2;
            if (!empty($RESULT_LIST)) {
                $pageNum = (int)$this->input->get('p');
                $pageSize = $view_page;
                $order = $this->input->get('o');
                if ($pageNum <= 1) $pageNum = 1;
                $totalRows = $this->model->getList(-1, -1, $type);
                $totalPage = ceil($totalRows / $pageSize);
                if ($pageNum > $totalPage) redirect(PATH_URL);
                $PAGINATION = pagination($totalRows, $pageNum, $pageSize);
                $startRow = ($pageNum - 1) * $pageSize;
                $RESULT_LIST = $this->model->getList($pageSize, $startRow, $type, $order);
                $TOTAL_LIST = $this->model->fetch('*', 'cli_books', "type = '{$type}' AND status = 1");
                $data = array(
                    'RESULT_LIST' => $RESULT_LIST,
                    'TOTAL_LIST' => $TOTAL_LIST,
                    'PAGINATION' => $PAGINATION,
                    'pageSize' => $pageSize,
                    'slug' => $slug,
                    'category' => ''
                );

            } else {
                $data = array(
                    'slug' => $slug,
                    'category' => ''
                );
            }
            $this->template->write_view('content', 'FRONTEND/type', $data);
            $this->template->write('meta_keywords', META_KEY);
            $this->template->write('meta_description', getDescription(typeSlugBook($slug, 'name')));
            $this->template->write('title', typeSlugBook($slug, 'name') . ' | ' . getSiteName());
            $this->template->render();
        } else {
            $CATEGORY = $this->model->get('*', 'cli_category', "slug = '{$slug}' AND status = 1");
            if (empty($CATEGORY)) {
                show_404();
            }
            $RESULT_LIST = $this->model->fetch('*', 'cli_books', "category_id = '{$CATEGORY->id}' AND status = 1", 'created', 'desc', 0, 2);
            $view_page = 1;
            if (!empty($RESULT_LIST)) {
                $pageNum = (int)$this->input->get('p');
                $pageSize = $view_page;
                $order = $this->input->get('o');
                if ($pageNum <= 1) $pageNum = 1;
                $totalRows = $this->model->getListCategory(-1, -1, $CATEGORY->id);
                $totalPage = ceil($totalRows / $pageSize);
                if ($pageNum > $totalPage) redirect(PATH_URL);
                $PAGINATION = pagination($totalRows, $pageNum, $pageSize);
                $startRow = ($pageNum - 1) * $pageSize;
                $RESULT_LIST = $this->model->getListCategory($pageSize, $startRow, $CATEGORY->id, $order);
                $TOTAL_LIST = $this->model->fetch('*', 'cli_books', "category_id = '{$CATEGORY->id}' AND status = 1");
                $data = array(
                    'CATEGORY' => $CATEGORY,
                    'RESULT_LIST' => $RESULT_LIST,
                    'TOTAL_LIST' => $TOTAL_LIST,
                    'PAGINATION' => $PAGINATION,
                    'pageSize' => $pageSize,
                    'category' => ''
                );
            } else {
                $data = array(
                    'CATEGORY' => $CATEGORY,
                    'category' => ''
                );
            }
            $this->template->write('meta_description', getDescription($CATEGORY->name . ': ' . strip_tags($CATEGORY->description)));
            $this->template->write('meta_keywords', META_KEY);
//                $parent_cate = $this->model->get('*', CATEGORY_NEWS_TB, 'id = ' . $CATEGORY->parent_id);
            $this->template->write('title', $CATEGORY->name . ' | ' . getSiteName());
            $this->template->write_view('content', 'FRONTEND/category', $data);
            $this->template->render();

        }
    }


    /*------------------------------------ End Admin Control Panel --------------------------------*/
}